//****************************************************
// Porman Project 2
// Filename: COcclusionQueryObject.cpp
// Date: 2009/09/21
// Author: KengYu Lin
// Modify:
//****************************************************
#include "CRenderDevice.h"
#include "COcclusionQueryObject.h"
#include "CAssert.h"

namespace Porman
{

namespace GL
{

COcclusionQueryObject::COcclusionQueryObject( CRenderDevice* pDevice ) :
CBaseObject(pDevice),
m_uiObjID(0)
{
    glGenQueries( 1, &m_uiObjID );
    if( m_uiObjID != 0 )
    {
        setName("Non");
        m_iNumOfQueriesObj++;
    }
    else
        throw 0;
}

COcclusionQueryObject::~COcclusionQueryObject( void )
{
    if( m_uiObjID != 0 )
    {
        glDeleteQueries( 1, &m_uiObjID );
        m_uiObjID = 0;
    }
    m_iNumOfQueriesObj--;
}

ERESULT COcclusionQueryObject::beginQuery( void )
{
    THREAD_CHECKING(m_pDeviceRef->getCurThreadID(), E_THREAD_ERROR);

    glBeginQuery( GL_SAMPLES_PASSED, m_uiObjID );
    if( glGetError() == GL_INVALID_OPERATION )
        return E_INVALID_OPERATION;
    else
        return E_SUCCESS;
}

ERESULT COcclusionQueryObject::endQuery( void )
{
    THREAD_CHECKING(m_pDeviceRef->getCurThreadID(), E_THREAD_ERROR);

    glEndQuery( GL_SAMPLES_PASSED );
    if( glGetError() == GL_INVALID_OPERATION )
        return E_INVALID_OPERATION;
    else
        return E_SUCCESS;
}

bool COcclusionQueryObject::queryResult( void )
{
    THREAD_CHECKING(m_pDeviceRef->getCurThreadID(), false);

    int iResult = 0;
    glGetQueryObjectiv( m_uiObjID, GL_QUERY_RESULT_AVAILABLE, &iResult );

    return iResult ? true : false;
}

int COcclusionQueryObject::getResult( void )
{
    THREAD_CHECKING(m_pDeviceRef->getCurThreadID(), 0);

    int iPixels = 0;
    glGetQueryObjectiv( m_uiObjID, GL_QUERY_RESULT, &iPixels );

    return iPixels;
}

}//End namespace GL

}//End namespace Porman